﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using qlqa.Delegate.AccountDelegate;
using qlqa.Delegate.TableDelegate;
using qlqa.Delegate.UserDelegate;
using qlqa.Models;
using qlqa.Models.Form.TableForm;

namespace qlqa.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        readonly AccountDelegate _accountDelegate = new AccountDelegate();
        readonly TableDelegate _tableDelegate = new TableDelegate();
        readonly UserDelegate _userDelegate = new UserDelegate();

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************
        [HttpPost]
        public JsonResult ChangePass(string oldpass, string newpass)
        {
            var username = Session["USERNAME"] != null ? Session["USERNAME"].ToString() : "";
            var user = _accountDelegate.GetUser(username, oldpass);
            if (user != null)
            {
                user.Password = newpass;

                var res = _userDelegate.CapNhatUser(user);
                return Json(res);
            }
            return Json(false);
        }

        public ActionResult LogOn()
        {
            var model = new LogOnModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            var loginResult = _accountDelegate.Login(model.UserName, model.Password);
            if (loginResult != null)
            {
                if (loginResult[0].Equals("1"))
                {
                    var user = _accountDelegate.GetUser(model.UserName, model.Password);
                    if (user != null)
                    {
                        Session["USERID"] = user.Id;
                        Session["USERNAME"] = user.Username;
                        Session["USERTEN"] = user.Ten;
                        Session["USERTYPE"] = user.UserType;
                        return RedirectToAction("QlTable", "Table");
                    }
                }
                else
                {
                    model.Message = loginResult[1];
                    return View("LogOn", model);
                }
            }
            model.Message = "Tài khoản không tồn tại!";
            return View("LogOn", model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            Session["USERID"] = null;
            Session["USERNAME"] = null;
            Session["USERTEN"] = null;
            Session["USERTYPE"] = null;
            FormsService.SignOut();

            return RedirectToAction("LogOn");
        }

        [HttpPost]
        public JsonResult CheckLogin()
        {
            if ( Session["USERID"] == null || Session["USERTEN"] == null || Session["USERNAME"] == null)
            {
                return Json(true);
            }
            return Json(false);
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
